package cn.leida.ruoyi.common.core.dao;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSONObject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import org.hibernate.query.sql.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lei
 * @create 2025-03-11 23:42
 */
public class BaseDao {
    @PersistenceContext
    protected EntityManager entityManager;

    public int queryCount(String countSql, List<Object> params) {
        Query totalQuery = entityManager.createNativeQuery(countSql);
        int size = params.size();
        for (int i = 0; i < size; i++) {
            totalQuery.setParameter(i + 1, params.get(i));
        }
        List<?> resultList = totalQuery.getResultList();
        if (resultList.isEmpty()) {
            return 0;
        }
        return NumberUtil.parseInt(resultList.get(0) + "", 0);
    }

    public List<JSONObject> queryData(String listSql, List<Object> listParams, Pageable pageable) {
        // 参数
        int listSize = listParams.size();
        Query contentQuery = entityManager.createNativeQuery(listSql);
        for (int i = 0; i < listSize; i++) {
            contentQuery.setParameter(i + 1, listParams.get(i));
        }
        // 查询map
        contentQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Object> results = contentQuery.getResultList();

        List<JSONObject> tables = new ArrayList<>();
        //  JSONObject
        for (Object obj : results) {
            JSONObject jsonObject = JSONObject.from(obj);
            tables.add(jsonObject);
        }
        // 分页参数
        if (pageable != null) {
            contentQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            contentQuery.setMaxResults(pageable.getPageSize());
        }
        return tables;
    }

    public List<JSONObject> queryData(String listSql, List<Object> listParams) {
        return queryData(listSql, listParams, null);
    }
}
